/**
 * 将food_data.json转换为TypeScript格式的食物数据
 */

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 读取food_data.json
const foodDataPath = path.join(__dirname, '../database/food_data.json');
const foodData = JSON.parse(fs.readFileSync(foodDataPath, 'utf8'));

console.log(`读取到 ${foodData.length} 种食物`);

// 转换为TypeScript格式
const convertToTS = (foods) => {
  const lines = ['// 从food_data.json自动生成的食物数据', 'const mockFoods: Partial<Food>[] = ['];
  
  foods.forEach((food, index) => {
    lines.push('  {');
    
    // 遍历所有字段
    Object.keys(food).forEach(key => {
      const value = food[key];
      if (value === null || value === undefined) {
        lines.push(`    ${key}: undefined,`);
      } else if (key === 'other_nutrients') {
        // 特殊处理other_nutrients
        if (typeof value === 'string') {
          if (value === '') {
            lines.push(`    ${key}: undefined,`);
          } else {
            try {
              const parsed = JSON.parse(value);
              lines.push(`    ${key}: ${JSON.stringify(parsed)},`);
            } catch (e) {
              lines.push(`    ${key}: undefined,`);
            }
          }
        } else if (Array.isArray(value)) {
          lines.push(`    ${key}: ${JSON.stringify(value)},`);
        } else {
          lines.push(`    ${key}: undefined,`);
        }
      } else if (typeof value === 'string') {
        // 空字符串转为undefined
        if (value === '') {
          lines.push(`    ${key}: undefined,`);
        } else {
          // 转义单引号和反斜杠
          const escaped = value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
          lines.push(`    ${key}: '${escaped}',`);
        }
      } else if (typeof value === 'boolean') {
        lines.push(`    ${key}: ${value},`);
      } else if (typeof value === 'number') {
        lines.push(`    ${key}: ${value},`);
      } else if (Array.isArray(value)) {
        lines.push(`    ${key}: ${JSON.stringify(value)},`);
      } else if (typeof value === 'object') {
        lines.push(`    ${key}: ${JSON.stringify(value)},`);
      }
    });
    
    // 添加时间戳字段（如果不存在）
    if (!food.created_at) {
      lines.push(`    created_at: '2024-01-01T00:00:00Z',`);
    }
    if (!food.updated_at) {
      lines.push(`    updated_at: '2024-01-01T00:00:00Z'`);
    }
    
    if (index < foods.length - 1) {
      lines.push('  },');
    } else {
      lines.push('  }');
    }
  });
  
  lines.push(']');
  
  return lines.join('\n');
};

// 生成TypeScript代码
const tsCode = convertToTS(foodData);

// 输出到临时文件
const outputPath = path.join(__dirname, '../src/stores/foods-data-generated.ts');
fs.writeFileSync(outputPath, tsCode, 'utf8');

console.log(`已生成 ${outputPath}`);
console.log('请手动将生成的数据复制到 src/stores/foods.ts 中');

